package com.xuanyang.dormrepair.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xuanyang.dormrepair.model.entity.Repairs;
import com.xuanyang.dormrepair.model.enums.RepairStatus;
import com.xuanyang.dormrepair.model.mapper.RepairsMapper;
import com.xuanyang.dormrepair.utils.PageKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;

/**
 * @AUTHOR soft
 * @DATE 2019/5/20 0:56
 * @DESCRIBE
 */
@Slf4j
@Service
public class RepairService {

    @Autowired
    private RepairsMapper repairsMapper;

    @Autowired
    private MaintainerService maintainerService;

    @Transactional
    public boolean add(Repairs repairs) {
        repairs.setDatetime(new Date());
        return repairsMapper.insert(repairs) > 0;
    }

    @Transactional
    public boolean delete(Serializable pk) {
        return repairsMapper.deleteById(pk) > 0;
    }

    public boolean updateId(Repairs repairs) {
        return repairsMapper.updateById(repairs) > 0;
    }

    @Transactional
    public boolean update(Repairs repairs, Repairs query) {
        LambdaQueryWrapper<Repairs> wrapper = Wrappers.lambdaQuery(query);

        return repairsMapper.update(repairs, wrapper) > 0;
    }

    public Repairs byId(Serializable pk) {
        return repairsMapper.selectById(pk);
    }

    public IPage<Repairs> page(int page, int limit, Repairs query) {
        LambdaQueryWrapper<Repairs> wrapper = Wrappers.lambdaQuery(query);
        wrapper.orderByDesc(Repairs::getId);

        return repairsMapper.selectPage(PageKit.of(page, limit), wrapper);
    }

    /**
     * 最新的报修数量
     */
    public int news() {
        LambdaQueryWrapper<Repairs> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Repairs::getStatus, RepairStatus.WAITING);
        return repairsMapper.selectCount(wrapper);
    }
}
